import { asyncRoutes, constantRoutes } from '@/router'/* Layout */
import Layout from '@/layout'
import { getMenus } from '@/api/user'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * @param routes (resolve: any) => require([`@/views/${view}.vue`], resolve)
 */
export function generaMenu(routes, data) {
  data.forEach(item => {
  // 这里的字段在实际业务开发中都有用的，当然如果只是简单学习的话，id，label可以移除
    const menu = {
      name: item.displayName,
      path: item.url,
      hidden: false,
      // alwaysShow: true,
      redirect: item.url,
      component: Layout, // item.url === '#' ? Layout : (resolve) => require([`@/views${item.url}`], resolve),
      meta: {
        // id: item.id,
        type: item.type,
        icon: 'nested',
        title: item.displayName
      },
      children: []
    }
    if (item.type === 2) {
      menu.hidden = true
    }
    if (item.items && item.items.length > 0) {
      generaMenu(menu.children, item.items)
    }
    routes.push(menu)
  })
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      const loadMenuData = []
      getMenus().then(response => {
        const data = response
        Object.assign(loadMenuData, data.items)
        const tempAsyncRoutes = Object.assign([], asyncRoutes)
        generaMenu(tempAsyncRoutes, loadMenuData)
        const accessedRoutes = tempAsyncRoutes || []
        // if (roles.includes('admin')) {
        //   accessedRoutes = tempAsyncRoutes || []
        // } else {
        //   accessedRoutes = filterAsyncRoutes(tempAsyncRoutes, roles)
        // }
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
